<?php
// +----------------------------------------------------------------------
// | YUEGONGBAO [ WE CAN DO IT MORE SIMPLE ]
// +----------------------------------------------------------------------
// | Copyright (c) 2013-2017 http://www.yuegongbaofund.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: 小夏 < 449134904@qq.com>
// +----------------------------------------------------------------------
namespace app\admin\controller;

use cmf\controller\AdminBaseController;
use dragon\AdminLogModel;
use think\Db;

class SystemController extends AdminBaseController
{
    
    const BACKUP_DIR = '../data/backup';
    const SQL_SEPARATOR = "\n/* ----------- Separator ------------ */\n";
    
    public function _initialize() {
        is_dir(self::BACKUP_DIR) or mkdir(self::BACKUP_DIR);
    }

    public function loglist()
    {
		$keyword = $this->request->param('keyword', '');
		$map = [];
		$keyword and $map['content'] = ['like', '%'.$keyword.'%'];
		
        $model	= new AdminLogModel();
		$model->where($map);
		$list	= $model->paginate(15);
		$page 	= $list->render();
		
        $this->assign('keyword', $keyword);
        $this->assign('list', $list);
        $this->assign('config', [
		]);
        $this->assign('page', $page);

        return $this->fetch();
    }
    
    public function backup() {
        $list = scandir(self::BACKUP_DIR, 1);
        
        foreach($list as $k => $v) {
            if($v{0} == '.') unset($list[$k]);
        }

        $this->assign('list', $list);
        return $this->fetch();
    }

    public function dobackup() {
        $tables = Db::query('SHOW TABLE STATUS FROM '.config('database.database'));
        
        $sql = '';
        foreach($tables as $v){
            $table = Db::query('SHOW CREATE TABLE '.$v['Name']);
            $sql .= "DROP TABLE IF EXISTS `".$v['Name']."`;";
            $sql .= self::SQL_SEPARATOR;
            $sql .= $table[0]['Create Table'].";";
            $sql .= self::SQL_SEPARATOR;
            
            $records = Db::query("select * from ".$v['Name']);
            if(!empty($records)){
                $insert = array();
                foreach($records as $key => $record){
                    foreach($record as $_k => $_v){
                        $insert[$_k] = "'".addslashes($_v)."'";
                    }
                    $sql .= "INSERT INTO `".$v['Name']."` VALUES(".implode(',', $insert).");";
                    $sql .= self::SQL_SEPARATOR;
                }
            }
        }
        
        $file = self::BACKUP_DIR.'/'.date('Y-m-d-H-i').'.sql';
        if(!file_put_contents($file, $sql)){
            return $this->error('备份失败,请检查文件夹是否有足够的权限');
        } else {
            return $this->success('备份成功');
        }
    }
    
    // 还原
    public function import() {
        $file = $this->request->param('source');
        
        $data = @file_get_contents(self::BACKUP_DIR.'/'.$file);
        $data = explode(self::SQL_SEPARATOR, trim($data));
        if(!empty($data)){
            foreach($data as $v){
                Db::execute($v);
            }
        }
        return $this->success('数据还原成功');
    }
    
    public function download() {
        $file = $this->request->param('source');
        
        $filePath = self::BACKUP_DIR.'/'.$file;
        
        header('Content-Description: File Transfer'); //描述页面返回的结果
        header('Content-Type: text/plain'); //返回内容的类型，此处只知道是二进制流。具体返回类型可参考http://tool.oschina.net/commons
        header('Content-Disposition: attachment; filename='.$file);//可以让浏览器弹出下载窗口
        header('Content-Transfer-Encoding: binary');//内容编码方式，直接二进制，不要gzip压缩
        header('Expires: 0');//过期时间
        header('Cache-Control: must-revalidate');//缓存策略，强制页面不缓存，作用与no-cache相同，但更严格，强制意味更明显
        header('Pragma: public');
        header('Content-Length: ' . filesize($filePath));//文件大小，在文件超过2G的时候，filesize()返回的结果可能不正确
        
        echo file_get_contents($filePath);
    }
}
